package com.dragon.gallery_paging

import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.dragon.gallery_paging.databinding.PhotoFragmentBinding


class photoFragment : Fragment() {
//    private lateinit var binding: PhotoFragmentBinding

    //viewBinding的使用
    private var _binding: PhotoFragmentBinding? = null
    private val binding get() = _binding!!

    companion object {
        fun newInstance() = photoFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = PhotoFragmentBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        //加入插件之后可直接调用id  减少findViewById的开支，从缓存中读取但是全局的，为kotlin的dataBinding的插件，可能会有调用错的问题
        binding.shimmer.apply {
            setShimmerAngle(0)
            setShimmerColor(0x55FFFFFF)
            startShimmerAnimation()
        }
        Glide.with(requireActivity())
            .load(arguments?.getParcelable<PhotoItem>("PHOTO")?.preViewUrl)
            .placeholder(R.drawable.ic_gray_24)
            .listener(object : RequestListener<Drawable>{
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false.also { binding.shimmer.stopShimmerAnimation() }
                }

            })
            .into(binding.photoView)
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

}